package com.jiubodou.myoauth2.config;

import com.jiubodou.myoauth2.oauth2class.jiubodou.JiuBoDouDaoAuthProvider;
import com.jiubodou.myoauth2.oauth2class.jiubodou.JiuBoDouUserDetailServiceImpl;
import com.jiubodou.myoauth2.oauth2class.my.MyDaoAuthenticationProvider;
import com.jiubodou.myoauth2.oauth2class.my.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName JiuBoDouSecurityConfig
 * @Description
 * @Author huyingliang
 * @Date 2023/5/12 11:37
 */
@Configuration
public class JiuBoDouAndMySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/jiubodou/**", "/oauth/**").permitAll()
                .anyRequest().authenticated();
        http.cors();/*允许跨域*/
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        /*这里可以使用 auth.authenticationProvider这个方法，一直添加 自己的 provider 因为其底层执行的是
         * this.authenticationProviders.add(authenticationProvider); 是往一个集合中添加元素*/
        JiuBoDouDaoAuthProvider jiuBoDouDaoAuthProvider = new JiuBoDouDaoAuthProvider();
        jiuBoDouDaoAuthProvider.setPasswordEncoder(passwordEncoder);
        jiuBoDouDaoAuthProvider.setUserDetailsService(new JiuBoDouUserDetailServiceImpl());
        jiuBoDouDaoAuthProvider.setHideUserNotFoundExceptions(false);
        auth.authenticationProvider(jiuBoDouDaoAuthProvider);

        MyDaoAuthenticationProvider myDaoAuthenticationProvider = new MyDaoAuthenticationProvider();
        myDaoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        myDaoAuthenticationProvider.setUserDetailsService(new MyUserDetailServiceImpl());
        myDaoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        auth.authenticationProvider(myDaoAuthenticationProvider);
    }

}
